package com.common.app.widget.calendarPickerView

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.GridLayout
import androidx.recyclerview.widget.RecyclerView
import com.common.app.R
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.CalendarMonth

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：17/7/2025
 *
 * 描述：月份视图适配器
 *
 * 修订历史：
 *
 */

/**
 * 月份视图适配器
 */
class CalendarMonthNewAdapter(
    private var months: List<CalendarMonth>,
    private val onDayClick: (CalendarDay) -> Unit
) : RecyclerView.Adapter<CalendarMonthNewAdapter.MonthViewHolder>() {

    private var selectedDay: CalendarDay? = null

    fun updateMonths(newMonths: List<CalendarMonth>) {
        months = newMonths
        notifyDataSetChanged()
    }

    fun setSelectedDay(day: CalendarDay?) {
        selectedDay = day
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MonthViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.calendar_month_layout, parent, false)

        // 确保ViewHolder的根视图填满ViewPager2
        view.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

        return MonthViewHolder(view)
    }

    override fun onBindViewHolder(holder: MonthViewHolder, position: Int) {
        holder.bind(months[position])
    }

    override fun getItemCount(): Int = months.size

    inner class MonthViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val gridLayout: GridLayout = itemView.findViewById(R.id.calendar_grid)

        fun bind(month: CalendarMonth) {
            gridLayout.removeAllViews()

            month.days.forEach { day ->
                val dayView = CalendarDayNewView(itemView.context)
                val updatedDay = day.copy(isSelected = day == selectedDay)
                dayView.setCalendarDay(updatedDay)

                dayView.setOnClickListener {
                    if (day.isCurrentMonth) {
                        onDayClick(day)
                    }
                }

                val params = GridLayout.LayoutParams().apply {
                    // 修复GridLayout参数设置
                    width = GridLayout.LayoutParams.WRAP_CONTENT
                    height = GridLayout.LayoutParams.WRAP_CONTENT
                    columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
                    rowSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
//                    // margin设置
//                    val margin = itemView.context.resources.getDimensionPixelSize(R.dimen.dp_1)
//                    setMargins(margin, margin, margin, margin)
                }

                gridLayout.addView(dayView, params)
            }
        }
    }
}